<template>
  <div class="app-container">
    <div
      v-show="
        !detailInfo.visible &&
        !detailListInfo.visible &&
        !modifyInfo.visible &&
        !planDetailInfo.visible
      "
    >
      <!-- 条件栏 -->
      <div class="filter-wrapper">
        <NewPageFilter
          v-model:query="filterInfo.query.queryMap"
          :query-more-json="true"
          :filter-list="filterInfo.searchList"
          :filter-btn="filterInfo.searchBtn"
          :clear-type="clearType"
          :slip-select-request="slipSelectRequest"
        >
        </NewPageFilter>
        <el-button @click="detailListInfo.visible = true">明细页</el-button>
      </div>
      <div class="filter-wrapper">
        <NewPageFilter :filter-btn="filterInfo.btnList">
          <template v-slot:filter-add>
            <el-button @click="showModify()">新增</el-button>
          </template>
          <template v-slot:filter-print>
            <el-button @click="print()">打印</el-button>
          </template>
          <template v-slot:filter-download>
            <el-button @click="exportExcel()">导出excel</el-button>
          </template>
        </NewPageFilter>
        <div class="display-flex">
          <el-button @click="preferenceInfo.visible = true">偏好设置</el-button>
        </div>
      </div>
      <!-- 表格 -->
      <table-container
        :refresh="tableInfo.refresh"
        :init-curpage="tableInfo.initCurpage"
        v-model:data="tableInfo.data"
        :api="tableInfo.api"
        :check-box="false"
        :tab-index="true"
        :query="filterInfo.query"
        :field-list="tableInfo.fieldList"
        :handle="tableInfo.handle"
        :row-class-name="tableRowClassName"
        @sortChange="sortChange"
        @handleEvent="handleEvent"
        @pageInfo="pageInfo"
      >
        <template v-slot:col-orderNo="scope">
          <span class="slip-edit" @click="showDetail(scope.row)">{{
            scope.row.orderNo
          }}</span>
        </template>
        <template v-slot:col-planOrderNo="scope">
          <span class="slip-edit" @click="showPlanDetail(scope.row)">{{
            scope.row.planOrderNo
          }}</span>
        </template>
        <template v-slot:col-remindDuration="scope">
          <span
            >{{ scope.row.remindDuration || 0 }}
            {{ scope.row.remindTimeTypeValue || '-' }}</span
          >
        </template>
        <template v-slot:col-createDuration="scope">
          <span
            >{{ scope.row.createDuration || 0 }}
            {{ scope.row.createTimeTypeValue || '-' }}</span
          >
        </template>
      </table-container>
    </div>

    <order-detail
      v-if="detailInfo.visible"
      v-model:visible="detailInfo.visible"
      :table-row-id="detailInfo.id"
      title="巡检任务详情"
      @returnBack="getList"
    />
    <order-modify
      v-if="modifyInfo.visible"
      v-model:visible="modifyInfo.visible"
      :id="modifyInfo.id"
      :title="modifyInfo.title"
      @returnBack="getList"
    />
    <set-preference
      v-if="preferenceInfo.visible"
      v-model:visible="preferenceInfo.visible"
      :search-list="filterInfo.searchList"
      :field-list="tableInfo.fieldList"
      :customize-user-v-o="filterInfo.query.customizeUserVO"
      :group-level-show="false"
      @callback="setPreferenceCallback"
    />
    <advanced-search
      v-if="advancedSearchInfo.visible"
      v-model:visible="advancedSearchInfo.visible"
      v-model:form-data="advancedSearchInfo.data"
      :field-list="tableInfo.fieldList"
      @callback="advancedSearchCallback"
    />
    <detailList
      v-if="detailListInfo.visible"
      v-model:visible="detailListInfo.visible"
      @callback="getList"
    ></detailList>
    <patrol-plan-detail
      v-if="planDetailInfo.visible"
      v-model:visible="planDetailInfo.visible"
      :table-row-id="planDetailInfo.id"
      title="巡检计划详情"
      @returnBack="getList"
    />
    <page-dialog
      v-if="dialogTipsInfo.visible"
      :title="dialogTipsInfo.title"
      v-model:visible="dialogTipsInfo.visible"
      :width="dialogTipsInfo.width"
      :bt-loading="dialogTipsInfo.btLoading"
      :bt-list="dialogTipsInfo.btList"
    >
      <div class="asset-msg">
        <div class="asset-msg-label">
          <i class="el-icon-warning"></i>{{ dialogTipsInfo.msg }}：
        </div>
        <el-radio-group v-model="dialogTipsInfo.flag">
          <el-radio :label="true">当前页数据</el-radio>
          <el-radio :label="false">全部页数据</el-radio>
        </el-radio-group>
      </div>
    </page-dialog>
  </div>
</template>

<script setup name="patrolTask">
import TableContainer from '@/components/TableContainer/index'
import { fatchTemplateByCode } from '@/api/base.js'
import OrderDetail from './details'
import OrderModify from './modify'
import patrolPlanDetail from '../patrolPlan/details'
import PageDialog from '@/components/PageDialog/index'
import { getCustomizeSetting, updateUserCustomize } from '@/api/customize'
import { getDepotAll } from '@/api/core'

import {
  getTaskPage,
  taskStart,
  taskCompleted,
  taskCancel,
  excelTaskOrderList,
  printTaskOrderList,
  deleteTask,
} from '@/api/patrol.js'

const { proxy } = getCurrentInstance()
const emit = defineEmits()

const SetPreference = defineAsyncComponent(() =>
  import('@/components/SetPreference/index')
)
const AdvancedSearch = defineAsyncComponent(() =>
  import('@/components/AdvancedSearch/index')
)
const detailList = defineAsyncComponent(() => import('./detailList'))

const storeState = proxy.$store.state
const clearType = ref(true)
const slipSelectRequest = ref(true)

const dialogTipsInfo = reactive({
  visible: false,
  title: '提示',
  btLoading: false,
  type: '',
  msg: '',
  width: '400px',
  flag: true,
  btList: [
    { label: '关闭', event: handleClose, show: true },
    {
      label: '打印',
      type: 'primary',
      event: checkConfirm,
      show: true,
    },
  ],
})
// 过滤相关配置
const filterInfo = reactive({
  sortArr: [],
  copyQueryMap: {},
  query: {
    sortString: '',
    customizeUserVO: {},
    queryMap: {},
  },
  searchList: [],
  searchBtn: [
    { type: 'button', label: '搜索', event: search },
    { type: 'button', label: '高级查询', event: advancedSearchShow },
    { type: 'button', label: '重置', event: clearSearch },
  ],
  btnList: [
    {
      type: 'slot',
      value: 'add',
      show: proxy.$permission('patrolTask:add'),
    },
    {
      type: 'slot',
      value: 'download',
      show: proxy.$permission('patrolTask:excelOrderList'),
    },
    {
      type: 'slot',
      value: 'print',
      show: proxy.$permission('patrolTask:printOrderList'),
    },
  ],
})
// 表格相关
const tableInfo = reactive({
  refresh: 1,
  initCurpage: 1,
  data: [],
  api: undefined,
  selections: [],
  fieldList: [],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '120',
    btList: [
      {
        label: '修改',
        event: showModify,
        show: proxy.$permission('patrolTask:modify'),
        ifRender: function (row) {
          return (
            row.status === 1 &&
            row.orderSource === 1 &&
            row.patrolPlanId === -2 &&
            (storeState.user.userInfo.user.type !== 'normal' ||
              row.createUser === storeState.user.userInfo.user.id)
          )
        },
      },
      {
        label: '删除',
        popconfirmText: '删除后将改变数据,是否继续？',
        event: remove,
        show: proxy.$permission('patrolTask:delete'),
        ifRender: function (row) {
          return (
            row.status === 1 &&
            row.orderSource === 1 &&
            row.patrolPlanId === -2 &&
            (storeState.user.userInfo.user.type !== 'normal' ||
              row.createUser === storeState.user.userInfo.user.id)
          )
        },
      },
      {
        label: '开始',
        event: start,
        show: proxy.$permission('patrolTask:start'),
        ifRender: function (row) {
          return (
            row.status === 1 &&
            row.orderSource === 1 &&
            (storeState.user.userInfo.user.type !== 'normal' ||
              row.execResponseUser == storeState.user.userInfo.user.id ||
              row.execCoordinationUser == storeState.user.userInfo.user.id)
          )
        },
      },
      {
        label: '执行任务',
        event: showDetail,
        show: true,
        ifRender: function (row) {
          return (
            row.status === 2 &&
            row.orderSource === 1 &&
            (storeState.user.userInfo.user.type !== 'normal' ||
              row.execResponseUser == storeState.user.userInfo.user.id ||
              row.execCoordinationUser == storeState.user.userInfo.user.id)
          )
        },
      },
      {
        label: '完成任务',
        event: complete,
        show: proxy.$permission('patrolTask:complete'),
        ifRender: function (row) {
          return (
            row.status === 2 &&
            row.orderSource === 1 &&
            (storeState.user.userInfo.user.type !== 'normal' ||
              row.execResponseUser == storeState.user.userInfo.user.id ||
              row.execCoordinationUser == storeState.user.userInfo.user.id)
          )
        },
      },
      {
        label: '取消任务',
        event: cancel,
        show: proxy.$permission('patrolTask:cancel'),
        ifRender: function (row) {
          return (row.status === 1 || row.status === 2) && row.orderSource === 1
        },
      },
    ],
  },
})

const detailInfo = reactive({
  visible: false,
  id: '',
})
const modifyInfo = reactive({
  visible: false,
  title: '',
  id: '',
})
const preferenceInfo = reactive({
  visible: false,
})
const advancedSearchInfo = reactive({
  visible: false,
  data: {},
})
const detailListInfo = reactive({
  visible: false,
})
const planDetailInfo = reactive({
  visible: false,
  id: '',
})
let page = reactive({
  curPage: 1, // 当前页
  pageSize: 20, // 每页条数
})

const toPage = computed(() => {
  return proxy.$store.state.settings.toPage
})

let stopWatch = function() {}
onActivated(() => {
  stopWatch = watch(
    () => toPage.value,
    (val) => {
      if (val) {
        let menus = proxy.$store.state.permission.defaultMenus
        menus.forEach((item) => {
          if (item.children) {
            item.children.forEach((el) => {
              if (el.code === 'patrolTask' && el.url === val.url) {
                preferenceInfo.visible = false
                advancedSearchInfo.visible = false
                detailListInfo.visible = false
                planDetailInfo.visible = false
                detailInfo.visible = false
                if (val.urlType === 1) {
                  getList()
                } else if (val.urlType === 2) {
                  detailInfo.visible = true
                  detailInfo.id = val.businessId
                  sessionStorage.setItem('storeRowId', val.businessId)
                }
                proxy.$store.dispatch('settings/toPage', '')
              }
            })
          }
        })
      }
    },
    {
      deep: true,
      immediate: true,
    }
  )
})
onDeactivated(() => {
  stopWatch()
})

let obj = {
  statusValue: {
    label: '状态',
    value: 'statusValue',
    asValue: 'status',
    componentType: 'select-model',
    code: 'patrol_task_status',
    show: false,
    hidden: true,
  },
  remindDuration: {
    label: '提醒时长',
    value: 'remindDuration',
    componentType: 'input',
    type: 'slot',
    show: false,
    hidden: true,
  },
  createDuration: {
    label: '生成于',
    value: 'createDuration',
    componentType: 'input',
    type: 'slot',
    show: false,
    hidden: true,
  },
  depotName: {
    label: '出库仓库',
    value: 'depotName',
    asValue: 'depotId',
    componentType: 'slip-select',
    query: {
      depotAuth: 'id',
      status: 1,
      useTypeId: '2',
    },
    api: getDepotAll,
    show: false,
    hidden: true,
  },
}
tableInfo.fieldList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...proxy.$fn.deepClone(obj),
})
filterInfo.searchList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...proxy.$fn.deepClone(obj),
})
getCustomize()

function start(row) {
  //开始
  taskStart(row.id).then((res) => {
    if (res && res.success) {
      getList()
    }
  })
}
function complete(row) {
  //完成
  proxy
    .$confirm('完成任务后巡检任务不能再修改,是否继续?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    .then(() => {
      taskCompleted(row.id).then((res) => {
        if (res && res.success) {
          getList()
        }
      })
    })
}
function cancel(row) {
  //取消
  proxy
    .$prompt('请输入取消原因', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      inputValidator: isNotEmptyString,
      inputErrorMessage: '请输入取消原因且不超过200字符',
    })
    .then(({ value }) => {
      const params = {
        id: row.id,
        cancelReason: value,
      }
      taskCancel(params).then((res) => {
        if (res && res.success) {
          getList()
        }
      })
    })
}
function isNotEmptyString(value) {
  if (value == null || typeof value === 'undefined' || value.trim() === '') {
    return false
  } else {
    if (value.length > 200) {
      return false
    }
    return true
  }
}
async function setPreferenceCallback(obj) {
  updateUserCustomize(obj.customizeUserVO).then((res) => {
    if (res && res.success) {
      getCustomize(!slipSelectRequest.value)
    }
  })
}
function pageInfo(obj) {
  page = obj
}
function handleClose() {
  dialogTipsInfo.visible = false
}
function checkConfirm() {
  if (dialogTipsInfo.type === 'excel') {
    exportExcelList()
  } else if (dialogTipsInfo.type === 'print') {
    printList()
  }
  dialogTipsInfo.visible = false
  dialogTipsInfo.msg = ''
}
function exportExcel() {
  //导出
  dialogTipsInfo.visible = true
  dialogTipsInfo.type = 'excel'
  dialogTipsInfo.msg = '请选择数据导出范围'
  dialogTipsInfo.btList[1].label = '导出'
  dialogTipsInfo.flag = true
}
function exportExcelList() {
  let params = {
    ...filterInfo.query,
    ...page,
    page: dialogTipsInfo.flag,
  }
  excelTaskOrderList(params).then((resp) => {
    if (resp) {
      proxy.$fn.parseExcel(resp)
    }
  })
}
function print() {
  //打印
  dialogTipsInfo.visible = true
  dialogTipsInfo.type = 'print'
  dialogTipsInfo.msg = '请选择当数据打印范围'
  dialogTipsInfo.btList[1].label = '打印'
  dialogTipsInfo.flag = true
}
function printList() {
  fatchTemplateByCode({
    resourceCode: 'patrolTask:printOrderList',
    isDefault: 1,
  }).then((res) => {
    if (res && res.success) {
      let temp = proxy.$fn.getPrintTemp(res.data[0])
      getPrintData(temp, dialogTipsInfo.flag)
    }
  })
}
function getPrintData(temp, flag) {
  let query = {
    customizeDto: filterInfo.query,
  }
  let params = {
    ...query,
    ...page,
    page: flag,
  }
  printTaskOrderList(params).then((res) => {
    if (res.success && res) {
      let data = proxy.$fn.deepClone(res.data)
      let newData = data.map((item) => {
        return {
          ...item,
          ...item.orderInfo,
        }
      })
      proxy.$lodop.preview(temp, newData)
    }
  })
}
function advancedSearchShow() {
  advancedSearchInfo.visible = true
}
async function advancedSearchCallback(obj) {
  filterInfo.query.queryMap = {}
  filterInfo.query.queryDtoList = [...obj.queryDtoList]
  advancedSearchInfo.data = obj.data
  await getList()
  clearType.value = !clearType.value
  filterInfo.query.queryMap = proxy.$fn.deepClone(filterInfo.copyQueryMap)
}
// 获取列表
async function getList() {
  tableInfo.refresh = Math.random()
}
// 搜索
function search() {
  // 重置分页
  advancedSearchInfo.data = {}
  filterInfo.query.queryDtoList = []
  tableInfo.initCurpage = Math.random()
  tableInfo.refresh = Math.random()
}
//展示明细
function showDetail(row) {
  sessionStorage.setItem('storeRowId', row.id)
  detailInfo.id = row.id
  detailInfo.visible = true
}
function tableRowClassName({ row }) {
  let rowId = sessionStorage.getItem('storeRowId')
  if (rowId && row.id === Number(rowId)) {
    return 'check-row'
  }
  return ''
}
//展示新增页
function showModify(row) {
  modifyInfo.title = '巡检任务新增'
  modifyInfo.id = ''
  if (row) {
    sessionStorage.setItem('storeRowId', row.id)
    modifyInfo.id = row.id
    modifyInfo.title = '巡检任务修改'
  }
  modifyInfo.visible = true
}
//删除
function remove(row) {
  deleteTask(row.id).then((resp) => {
    if (resp && resp.success) {
      getList()
    }
  })
}
function showPlanDetail(row) {
  planDetailInfo.id = row.patrolPlanId
  planDetailInfo.visible = true
}
// 触发事件
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.selections = [...data]
      break
  }
}
function clearSearch() {
  clearType.value = !clearType.value
  advancedSearchInfo.data = {}
  filterInfo.query.queryMap = proxy.$fn.deepClone(filterInfo.copyQueryMap)
  search()
}
function getCustomize(_slipSelectRequest = true) {
  let param = {
    tableKey:
      'patrolTaskOrderList-com.slip.spd.entity.vo.patrol.PatrolTaskOrderVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      filterInfo.query.customizeUserVO = data
      tableInfo.fieldList = proxy.$fn.setFieldList(
        tableInfo.fieldList,
        data.detail
      )
      let searchInfo = proxy.$fn.setSearchList(
        filterInfo.searchList,
        data.detail
      )
      filterInfo.query.queryMap = {
        ...searchInfo.queryMap,
        ...filterInfo.query.queryMap,
      }
      filterInfo.searchList = searchInfo.searchList
      filterInfo.searchList.forEach((item) => {
        item.event = search
      })
      filterInfo.copyQueryMap = proxy.$fn.deepClone(filterInfo.query.queryMap)
      slipSelectRequest.value = _slipSelectRequest
      tableInfo.api = getTaskPage
      getList()
    }
  })
}
function sortChange(column) {
  if (filterInfo.query.customizeUserVO.head.sortType === 0) {
    let arr = proxy.$fn.sortChange(column, filterInfo.sortArr)
    filterInfo.sortArr = arr
    filterInfo.query.sortString = arr.length ? arr.toString() : ''
    getList()
  }
}
</script>

<style scoped lang="scss">
.dialogInfo-form-title {
  width: 100%;
  padding-left: 10px;
  color: #6dc1a9;
  margin-bottom: 20px;
  span {
    color: rgb(95, 91, 91);
    font-size: 12px;
  }
}
</style>
